const { readUser } = require ('../file/user');
/**
 * 用户登录
 * @param {*} data 登录参数
 */
async function userLogin(data) {
    console.log('参数',data);
    try {
        const res = await readUser();
        // 返回登录状态
        const resData = {
            code: 200,
            msg: '登录成功'
        }
        // 判断是否存在用户
        const index = res.findIndex((item) => item.name === data.name);
        console.log('index', index);
        if( index < 0 ){
            resData.code = 500;
            resData.msg = '用户不存在！';
            return Promise.resolve(resData);
        }else{
            const user = res[index];
            if(user.password !== data.password){
                resData.code = 500;
                resData.msg = '用户或密码不正确！';
                return Promise.resolve(resData);
            }
        }
        resData.data = res[index];
        return Promise.resolve(resData);
    } catch (error) {
        return Promise.reject(error);
    }
}

/**
 * 用户注册
 * @param {*} data 
 * @returns 
 */
async function userRegister(data) {
    try {
        const res = await readUser();
        // 返回登录状态
        const resData = {
            code: 200,
            msg: '注册成功！'
        }
        // 判断是否存在用户
        const index = res.findIndex((item) => item.name === data.username);
        console.log('index', index);
        if( index > -1 ){
           resData.code = 500;
           resData.msg = '该账号已被注册！';
           return Promise.resolve(resData);
        }
    }catch (error) {
        return Promise.reject(error);
    }
}

exports.userLogin = userLogin;
exports.userRegister = userRegister;
